import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { Form, Button, Transfer } from 'antd';

import FormCondition from '@/components/FormCondition';
import DrawerCondition from '@/components/DrawerCondition';

const SysMenuSet = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading } = props;
  const { show = false, detail = {} } = visible;
  const { allList = [], roleList } = detail;
  const [form] = Form.useForm();
  const [targetKeys, setTargetKeys] = useState([]);
  const fetchMenuEdit = () => {
    form.validateFields().then((values) => {
      const { id } = detail;
      const payload = { ...detail, ...values, id, roleIdList: targetKeys };
      dispatch({
        type: 'setting/fakeAuthAdmin',
        payload,
        callback: () => {
          onClose();
          handleCallback();
        },
      });
    });
  };

  useEffect(() => {
    if (!show) {
      setTargetKeys([]);
    } else {
      if (roleList) {
        setTargetKeys(
          roleList.map((item) => {
            return item.id;
          }),
        );
      }
    }
  }, [show]);
  const formItems = [
    {
      label: '管理员账号',
      name: 'username',
      maxLength: 10,
    },
    {
      label: '管理员姓名',
      name: 'truename',
    },
    {
      label: '超管标识',
      type: 'select',
      name: 'flag',
      select: ['否', '是'],
      rules: [{ required: false }],
    },

    {
      label: '手机',
      name: 'mobile',
    },
    {
      label: '邮箱',
      name: 'email',
      rules: [{ required: false }],
    },
    {
      label: '状态',
      name: 'status',
      type: 'radio',
      select: ['禁用', '启用'],
    },
    {
      type: 'noForm',
      label: '关联角色',
      formItem: (
        <div>
          <Transfer
            style={{ margin: '0 auto', justifyContent: 'center' }}
            titles={['未关联角色', '已关联角色']}
            render={(item) => item.title}
            onChange={(e, i) => {
              setTargetKeys(e);
            }}
            targetKeys={targetKeys}
            dataSource={allList.map((item) => {
              return {
                ...item,
                key: item.id,
                title: item.roleName,
              };
            })}
          ></Transfer>
        </div>
      ),
    },
  ];

  const modalProps = {
    title: `菜单设置 - ${detail.menuName || detail.accessName || '新增'}`,
    visible: show,
    onClose,
    footer: (
      <Button type="primary" loading={loading} onClick={fetchMenuEdit}>
        确定
      </Button>
    ),
  };

  return (
    <DrawerCondition {...modalProps}>
      <FormCondition form={form} formItems={formItems} initialValues={detail}></FormCondition>
    </DrawerCondition>
  );
};

export default connect(({ setting, loading }) => ({
  loading: loading.effects['setting/fakeAuthAdmin'],
}))(SysMenuSet);
